package org.light.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.generator.NamedStatementGenerator;
import org.light.generator.NamedStatementListGenerator;
import org.light.utils.InterVarUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class Add extends Verb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.sql.Connection");
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport("java.util.ArrayList");
		method.addAdditionalImport("java.sql.PreparedStatement");
		method.addAdditionalImport("java.sql.ResultSet");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
		method.addSignature(new Signature(1,InterVarUtil.DB.connection.getVarName(),InterVarUtil.DB.connection.getVarType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(NamedStatementGenerator.getAddSqlStatement(1000L,2, this.domain,InterVarUtil.DB.query));
		list.add(NamedStatementGenerator.getPrepareStatementWithReturnGeneratedKeys(2000L,2, InterVarUtil.DB.ps, InterVarUtil.DB.query, InterVarUtil.DB.connection));
		list.add(NamedStatementListGenerator.generatePsSetDomainFieldsWithoutId(3000L, 2,this.domain, InterVarUtil.DB.ps));
		list.add(NamedStatementGenerator.getPrepareStatementExcuteUpdate(4000L,2, InterVarUtil.DB.result, InterVarUtil.DB.ps));
		list.add(NamedStatementListGenerator.generateResultReturnSuccessUpdatedDomainId(5000L,2, InterVarUtil.DB.result,InterVarUtil.DB.ps,this.domain));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}
	
	

	@Override
	public Method generateDaoMethodDefinition() {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.sql.Connection");
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		
		method.addSignature(new Signature(1,InterVarUtil.DB.connection.getVarName(),InterVarUtil.DB.connection.getVarType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		return method;
	}

	@Override
	public Method generateServiceMethodDefinition() {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		return method;
	}

	@Override
	public Method generateServiceImplMethod() {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.sql.Connection");
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addAdditionalImport(this.domain.getPackageToken()+".database.DBConf");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoimplSuffix()+"."+this.domain.getStandardName()+"DaoImpl");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
	
		
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		
		//Service method
		Method daomethod = this.generateDaoMethodDefinition();
				
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(NamedStatementListGenerator.generateServiceImplReturnBoolean(1000L, 2, InterVarUtil.DB.connection, InterVarUtil.DB.dbconf, InterVarUtil.DB.dao, daomethod));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}
	
	public Add(){
		super();
	}
	
	public Add(Domain domain){
		super();
		this.domain = domain;
		this.setVerbName("Add"+StringUtil.capFirst(this.domain.getStandardName()));
	}

	@Override
	public Method generateControllerMethod() {
		Method method = new Method();
		method.setStandardName("processRequest");
		method.setReturnType(new Type("void"));
		method.setThrowException(true);
		List<String> list = new ArrayList<String>();
		list.add("ServletException");
		list.add("IOException");
		method.setIsprotected(true);
		method.setOtherExceptions(list);
		method.addSignature(new Signature(1,"request",new Type("HttpServletRequest","javax.servlet.http")));
		method.addSignature(new Signature(2,"response",new Type("HttpServletResponse","javax.servlet.http")));
		method.addAdditionalImport("java.io.IOException");
		method.addAdditionalImport("java.io.PrintWriter");
		method.addAdditionalImport("javax.servlet.ServletException");
		method.addAdditionalImport("javax.servlet.http.HttpServlet");
		method.addAdditionalImport("javax.servlet.http.HttpServletRequest");
		method.addAdditionalImport("javax.servlet.http.HttpServletResponse");
		method.addAdditionalImport("java.util.Map");
		method.addAdditionalImport("java.util.TreeMap");
		method.addAdditionalImport("net.sf.json.JSONObject");
		method.addAdditionalImport("java.io.BufferedReader");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceimplSuffix()+"."+this.domain.getStandardName()+"ServiceImpl");
		if (this.domain.containsDateTime()) {
		  method.addAdditionalImport(this.domain.getPackageToken()+".utils.DateUtil");
		}
		
		List<Writeable> wlist = new ArrayList<>();
		Var service = new Var("service", new Type(this.domain.getStandardName()+"Service",this.domain.getPackageToken()));
		Var resultMap = new Var("result", new Type("TreeMap<String,Object>","java.util"));
		wlist.add(NamedStatementGenerator.getFacadeSetContentType(1000L, 2, InterVarUtil.Servlet.response, InterVarUtil.SimpleJEE.UTF8.getVarName()));
		wlist.add(NamedStatementGenerator.getControllerPrintWriterOut(2000L, 2, InterVarUtil.Servlet.response, InterVarUtil.Servlet.out));
		wlist.add(NamedStatementGenerator.getJsonResultMap(2500L, 2, resultMap));
		wlist.add(NamedStatementGenerator.getTryHead(3000L, 2));
		wlist.add(NamedStatementGenerator.getPrepareDomainVarInit(4000L, 3, this.domain));
		wlist.add(NamedStatementListGenerator.generateJsonRequest(5500L, 3, InterVarUtil.Servlet.request));
		wlist.add(NamedStatementListGenerator.generateSetDomainDataWithoutIdFromJsonRequest(6000L, 3, this.domain, InterVarUtil.Servlet.jsonRequest));
		wlist.add(NamedStatementGenerator.getPrepareService(7000L,3, service));
		
		long serial = 8000L;
		boolean imageExists = false;
		for (Field f : this.domain.getPlainFields()) {
			if (f.getFieldType().equalsIgnoreCase("image")) {
				imageExists = true;
				wlist.add(new Statement(serial, 3,
						"if (" + this.domain.getCapFirstDomainName()+"ServiceImpl.temp" + this.domain.getCapFirstDomainName() + "!=null && " + this.domain.getCapFirstDomainName()+"ServiceImpl.temp"
								+ this.domain.getCapFirstDomainName() + ".get" + f.getCapFirstFieldName()
								+ "()!=null) {"));
				wlist.add(new Statement(serial + 1000L, 4,
						this.domain.getLowerFirstDomainName() + ".set" + f.getCapFirstFieldName() + "(" + this.domain.getCapFirstDomainName()+"ServiceImpl.temp"
								+ this.domain.getCapFirstDomainName() + ".get" + f.getCapFirstFieldName()
								+ "());"));
				wlist.add(new Statement(serial + 2000L, 3, "}"));
				serial += 3000L;
			}
		}
		if (imageExists) {
			wlist.add(new Statement(serial + 1000L, 3, this.domain.getCapFirstDomainName()+"ServiceImpl.temp" + this.domain.getCapFirstDomainName() + " = new  "
					+ this.domain.getCapFirstDomainNameWithSuffix() + "();"));
			serial += 2000L;
		}

		wlist.add(NamedStatementGenerator.getCallServiceMethodAssignSuccess(serial + 1000L, 3, service, generateServiceMethodDefinition()));
		wlist.add(NamedStatementListGenerator.getPutJsonResultMapWithSuccessAndDomain(serial + 2000L, 3, resultMap,this.domain));
		wlist.add(NamedStatementGenerator.getEncodeMapToJsonResultMap(serial + 3000L, 3, resultMap,InterVarUtil.Servlet.out));
		wlist.add(NamedStatementListGenerator.generateCatchExceptionPrintStackPrintJsonMapFinallyCloseOutFooter(serial + 4000L, 2, InterVarUtil.Servlet.response, resultMap, InterVarUtil.Servlet.out));
		method.setMethodStatementList(WriteableUtil.merge(wlist));
		
		return method;
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		JavascriptBlock block = new JavascriptBlock();
		block.setSerial(100);
		block.setStandardName("add"+domain.getCapFirstDomainName());
		StatementList sl = new StatementList();
		sl.add(new Statement(1000,0, "{"));
		sl.add(new Statement(2000,1, "text:'新增',"));
		sl.add(new Statement(3000,1, "iconCls:'icon-add',"));
		sl.add(new Statement(4000,1, "handler:function(){"));
		sl.add(new Statement(5000,2, "$('#wadd"+this.domain.getCapFirstDomainName()+"').window('open');"));
		sl.add(new Statement(6000,1, "}"));
		sl.add(new Statement(7000,0, "}"));
		block.setMethodStatementList(sl);
		return block;			
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		Domain domain = this.domain;
		JavascriptMethod method = new JavascriptMethod();
		method.setSerial(200);
		method.setStandardName("add"+domain.getCapFirstDomainName());
		
		StatementList sl = new StatementList();
		sl.add(new Statement(1000,1, "if ($(\"#ff\").form(\"validate\")) {"));
		sl.add(new Statement(2000,2, "$.ajax({"));
		sl.add(new Statement(3000,3, "type: \"post\","));
		sl.add(new Statement(4000,3, "url: \"../"+domain.getControllerPackagePrefix()+domain.getLowerFirstDomainName()+domain.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
		sl.add(new Statement(5000,3, "data: JSON.stringify({"));
		long serial = 6000;
		for (Field f: domain.getFieldsWithoutId()){
			if (f instanceof Dropdown){
				sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+f.getLowerFirstFieldName()+"\").combobox(\"getValue\"),"));
			} else if (f.getFieldType().equalsIgnoreCase("boolean")){
				sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":parseBoolean($(\"#ff\").find(\"input[name='"+f.getLowerFirstFieldName()+"']:checked\").val()),"));								
			} else {
				sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+f.getLowerFirstFieldName()+"\").val(),"));
			}
			serial+=1000;
		}				
		sl.add(new Statement(serial,3, "}),"));
		sl.add(new Statement(serial+1000, 2, "dataType: 'json',"));
		sl.add(new Statement(serial+2000, 2, "contentType:\"application/json;charset=UTF-8\","));
		sl.add(new Statement(serial+3000,3, "success: function(data, textStatus) {"));
		sl.add(new Statement(serial+4000,4, "if (data.success) {"));
		sl.add(new Statement(serial+5000,5, "$('#ff').form('clear');"));
		sl.add(new Statement(serial+6000,5, "$(\"#ff\").find(\"input[name='"+domain.getActive().getLowerFirstFieldName()+"']\").get(0).checked = true;"));
		sl.add(new Statement(serial+7000,5, "$(\"#wadd"+domain.getCapFirstDomainName()+"\").window('close');"));
		sl.add(new Statement(serial+8000,5, "$(\"#dg\").datagrid(\"load\");"));
		sl.add(new Statement(serial+9000,4, "}"));
		sl.add(new Statement(serial+10000,4, "},"));
		sl.add(new Statement(serial+11000,3, "complete : function(XMLHttpRequest, textStatus) {"));
		sl.add(new Statement(serial+12000,3, "},"));
		sl.add(new Statement(serial+13000,3, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
		sl.add(new Statement(serial+14000,4, "alert(\"Error:\"+textStatus);"));
		sl.add(new Statement(serial+15000,4, "alert(errorThrown.toString());"));
		sl.add(new Statement(serial+16000,3, "}"));
		sl.add(new Statement(serial+17000,2, "});"));
		sl.add(new Statement(serial+18000,1, "}"));
		
		method.setMethodStatementList(sl);
		return method;	
	}
	
	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(StringUtil.lowerFirst(getVerbName()));
			method.setReturnType(new Type("boolean"));
			method.setThrowException(true);
			method.addAdditionalImport(this.domain.getPackageToken() + "." + this.domain.getDomainSuffix() + "."
					+ this.domain.getCapFirstDomainNameWithSuffix());
			method.addSignature(
					new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
						
			List<Writeable> sList = new ArrayList<Writeable>();		
			sList.add(new Statement(1000L,2, this.domain.getCapFirstDomainNameWithSuffix()+" "+this.domain.getLowerFirstDomainName()+"0 = "+this.domain.getLowerFirstDomainName()+".clone();"));
			sList.add(new Statement(2000L,2, this.domain.getLowerFirstDomainName()+"0.set"+this.domain.getDomainId().getCapFirstFieldName()+"(maxId()+1);"));
			sList.add(new Statement(3000L,2,"db.add("+this.domain.getLowerFirstDomainName()+"0);"));
			sList.add(new Statement(4000L,2,"return true;"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public Method generateDummyServiceImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoimplSuffix()+"."+this.domain.getStandardName()+"DummyDaoImpl");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		
		Method daomethod = this.generateDummyDaoMethodDefinition();				
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(NamedStatementListGenerator.generateDummyServiceImplReturnBoolean(1000L, 2, InterVarUtil.DB.dao, daomethod));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}

	@Override
	public Method generateDummyDaoMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
		method.setReturnType(new Type("boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
		return method;
	}
}
